/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.chalmers.fatclient.sb;

import AirLine.Booking;
import Database.Flights;
import Database.UnableToBookException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;
import javax.ejb.Stateful;

/**
 *
 * @author hajo
 */
@Stateful
public class FatClientSBBean implements FatClientSBRemote {

    public FatClientSBBean() {
        if (flights == null) {
            flights = new Flights();
            try {
                flights.populate();
            } catch (SQLException e) {
                log(e.getMessage());
            }

        }
    }
    private Flights flights;
    private String ERROR_MESSAGE = "";

    public TreeSet<Flight> getFlights() {
        if (flights == null) {
            flights = new Flights();
            try {
                flights.populate();
                return flights.getFlightsList();
            } catch (SQLException e) {
                log(e.getMessage());
            }

        } else {
            try {
                return flights.getFlightsList();
            } catch (SQLException e) {
                log(e.getMessage());
            }
        }
        
        return new TreeSet<Flight>();

    }

    private void log(String s) {
        System.out.println(s);
        ERROR_MESSAGE += " \n " + s;
    }

    public boolean error() {
        return ERROR_MESSAGE.length() != 0;
    }

    public String getErrorMessage() {
        String error_m = ERROR_MESSAGE;
        ERROR_MESSAGE = "";
        return error_m;
    }

    public boolean book(ArrayList<Booking> b) {

        Iterator<Booking> it = b.iterator();
        try {
            flights.connect();
            flights.setSavePoint();
        } catch (SQLException e) {
            log(e.getMessage());
            try {
                flights.closeConnections();
            } catch (SQLException e2) {
                log(e2.getMessage());
            }
            return false;
        }
        try {

            while (it.hasNext()) {
                Booking booking = it.next();



                flights.book(booking);
            }
            flights.commit();
        } catch (SQLException e) {
            log(e.getMessage());
            try {
                flights.rollBack();
            } catch (SQLException e2) {
                log(e2.getMessage());
            }
            return false;
        } catch (UnableToBookException e) {
            log("Unable to book :");
            log(e.getMessage());
            return false;
        } finally {
            try {
                flights.update();
                flights.closeConnections();
            } catch (SQLException e) {
                log(e.getMessage());
            }
        }
        return true;
    }
}
